package br.com.sovi.gwt.client.historico.infowindow;

import br.com.sovi.gwt.client.application.Application;
import br.com.sovi.gwt.client.application.ApplicationConstants;
import br.com.sovi.gwt.client.application.SingleAttributeListener;
import br.com.sovi.gwt.client.historico.ChangePontoClickHandler;
import br.com.sovi.gwt.client.historico.HistoricoMarker;
import br.com.sovi.gwt.client.historico.marcador.MarcadorInfoController;

import com.google.gwt.maps.client.InfoWindow;
import com.google.gwt.maps.client.InfoWindowContent;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class HistoricoInfoWindow {

	private final MapWidget map;

	private InfoWindow infoWindow;

	public HistoricoInfoWindow(MapWidget map) {
		this.map = map;
		infoWindow = map.getInfoWindow();

		Application.get().addAttributeListener(
				new SingleAttributeListener(ApplicationConstants.HISTORICO_MARCADOR_SELECIONADO) {
					@Override
					public void added(Object value) {
						if (value != null) {
							showInfoWindow();
						}
					}

					@Override
					public void removed() {
						infoWindow.close();
					}
				});
	}

	public void showInfoWindow() {
		infoWindow.close();

		InfoWindowContent content = new InfoWindowContent(buildContent());
		content.setMaxWidth(300);

		infoWindow.open(MarcadorInfoController.getMarker().getLatLng(), content);
		infoWindow.setMaximizeEnabled(true);

		map.setInfoWindowEnabled(true);
	}

	VerticalPanel mainPanel;

	private Widget buildContent() {
		mainPanel = new VerticalPanel();
		mainPanel.setSpacing(5);

		mainPanel.add(buildNavigationButtons());

		mainPanel.add(buildServerTime());

		return mainPanel;
	}

	private Widget buildServerTime() {
		Label label = new Label();
		label.setStyleName("cuiw_dataServidorLabel");

		String data = MarcadorInfoController.getDataServidor();

		label.setText(data);

		return label;
	}

	private HorizontalPanel buildNavigationButtons() {
		HorizontalPanel pontosPanel = new HorizontalPanel();

		HistoricoMarker next = MarcadorInfoController.getNextMarker();
		HistoricoMarker previous = MarcadorInfoController.getPreviousMarker();

		Button previousButton = new Button("Anterior", new ChangePontoClickHandler(previous, map));
		pontosPanel.add(previousButton);
		previousButton.setEnabled(previous != null);

		Button nextButton = new Button("Próximo", new ChangePontoClickHandler(next, map));
		pontosPanel.add(nextButton);
		nextButton.setEnabled(next != null);

		return pontosPanel;
	}

}
